﻿#include "RTTScence.h"

#include "Camera.h"
#include "CubMapScene.h"
#include "Debuger.h"
#include "RanderTarget.h"
#include "Render.h"
#include "MaterialSrc/CubeMaterial.h"
#include "MaterialSrc/DrawImgMaterial.h"
#include "DefaultMeshFactory.h"

void FRTTScene::Init(FRender* InRender)
{
	FScence::Init(InRender);

	Camera = CreateDefaultCamera();

	const auto Material = std::make_shared<FCubeMaterial>();
	Material->Init();

	CubeMesh = FDefaultMeshFactory::CreateCube(FDefaultMeshFactory::ECubeVertexType::PosUV);
	CubeMesh->SetMaterial(Material);


	FTextureBuild Build;
	Texture = Build
		.SetSize(1920, 1080)
		.SetFormat(GL_RGB)
		.SetInternalFormat(GL_RGB)
		.SetTextureData(GL_UNSIGNED_BYTE, nullptr)
		.SetFilter(ETextureTypes::Filter::Linear)
		.Build();

	RanderTarget = std::make_shared<FRanderTarget>();
	auto [Ok, Index] = RanderTarget->BindTextureAsColorAttach(Texture, "MyRTTTexture");
	DebugerAssert(Ok, "%hs", "RTT Bind Texture 失败");

	// 这里的深度缓存是必须的 因为 场景中的立方体 如果没有 Depth ，就会导致显示错误
	Ok =RanderTarget->BindRanderBufferAsDepthAttach(1920, 1080);
	DebugerAssert(Ok, "%hs", "RTT BindRanderBufferAsDepthAttach 失败");


	const auto ImgMaterial = std::make_shared<FDrawImgMaterial>();
	ImgMaterial->SetTexture(Texture);
	ImgMaterial->Init();

	ImgMesh = FDefaultMeshFactory::CreateQuad();
	ImgMesh->SetMaterial(ImgMaterial);
	ImgMesh->OnCheckEnabledSetShaderData = [](std::map<std::string, bool>& EnabledSetMap)
	{
		EnabledSetMap["view"] = false;
		EnabledSetMap["projection"] = false;
	};

}

void FRTTScene::Destory()
{
	FScence::Destory();
}

void FRTTScene::Draw(float DateTime)
{
	FScence::Draw(DateTime);


	auto Projection = glm::mat4(1.f);
	Projection = glm::perspective(glm::radians(Camera->GetFOV()), Render->GetAspect(), 0.1f, 100.0f);

	FDrawArg DrawArg;
	DrawArg.DateTime = DateTime;
	DrawArg.LightArray = { };
	DrawArg.ViewMat = Camera->GetViewMat();
	DrawArg.ViewPos = Camera->GetPosition();
	DrawArg.ProjectionMat = Projection;

	RanderTarget->Used();

	CubeMesh->Draw(DrawArg);

	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

	CubeMesh->Draw(DrawArg);
	
	auto Mat = glm::mat4(1.0);
	Mat = glm::scale(Mat, glm::vec3(0.4f));
	Mat = glm::translate(Mat, glm::vec3(1.2f, 1.2f, 0.f));
	ImgMesh->SetTransform(Mat);

	auto DrawArgCopy = DrawArg;
	DrawArgCopy.ViewMat = glm::mat4(1.0f);
	ImgMesh->Draw(DrawArgCopy);


}
